using System;
using System.Collections.Generic;
using System.Text;
using Kevin.Framework.Data.Configuration;
using System.Web.Configuration;
using System.Configuration.Provider;

namespace Kevin.Framework.Data.Provider
{
    public static class CurrentProvider
    {
        #region Provider model

        private static BuilderProvider _provider;
        private static BuilderProviderCollection _providers;
        private static object _lock = new object();

        /// <summary>
        /// Gets the current provider.
        /// </summary>
        public static BuilderProvider Provider
        {
            get { LoadProviders(); return _provider; }
        }

        /// <summary>
        /// Gets a collection of all registered providers.
        /// </summary>
        public static BuilderProviderCollection Providers
        {
            get { LoadProviders(); return _providers; }
        }

        /// <summary>
        /// Load the providers from the web.config.
        /// </summary>
        private static void LoadProviders()
        {
            // Avoid claiming lock if providers are already loaded
            if (_provider == null)
            {
                lock (_lock)
                {
                    // Do this again to make sure _provider is still null
                    if (_provider == null)
                    {
                        /*
                        // Get a reference to the <blogProvider> section
                        BuilderProviderSection section = (BuilderProviderSection)WebConfigurationManager.GetSection("framework/orm");
                       
                        // Load registered providers and point _provider
                        // to the default provider
                        
                        _providers = new BuilderProviderCollection();
                        ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(BuilderProvider));
                        _provider = _providers[section.DefaultProvider];
                         //*/
                        _provider = new SqlServerProvider();
                        if (_provider == null)
                            throw new ProviderException("Unable to load default BlogProvider");
                    }
                }
            }
        }

        #endregion
    }
}
